<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">出库红冲作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="info-section">
      <view class="section-header">
        <text class="section-title">查询信息</text>
      </view>
      <view class="info-form">
        <view class="form-item">
          <text class="form-label">查询日期</text>
          <picker
            mode="date"
            :value="formData.queryDate"
            @change="handleDateChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{ formData.queryDate }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
        <view class="form-item">
          <text class="form-label">仓库</text>
          <picker
            mode="selector"
            :range="targetWarehouseOptions"
            range-key="text"
            :value="currentWarehouseIndex"
            @change="handleWarehouseChange"
          >
            <view class="warehouse-picker">
              <text class="warehouse-display">{{
                currentWarehouse ? currentWarehouse.warehouseName : "请选择仓库"
              }}</text>
              <text class="picker-arrow">▼</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- C. 时间筛选按钮组 -->
    <view class="search-section">
      <view class="section-header">
        <text class="section-title">查询条件</text>
        <view class="time-filter-buttons">
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'today' }"
            @tap="handleTimeChange('today')"
          >
            当日
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'week' }"
            @tap="handleTimeChange('week')"
          >
            近7天
          </button>
          <button
            class="filter-btn"
            :class="{ active: timeFilter === 'month' }"
            @tap="handleTimeChange('month')"
          >
            近1个月
          </button>
        </view>
      </view>
    </view>

    <!-- D. 主表数据 -->
    <view class="material-table-section">
      <view class="section-header">
        <text class="section-title">出库单列表</text>
        <view class="statistics-info">
          <text class="stat-item">主表数量: {{ mainTableData.length }}</text>
        </view>
      </view>
      <scroll-view class="table-scroll" scroll-y>
        <view class="table-row header">
          <text class="header-cell">选择</text>
          <text class="header-cell">创建时间</text>
          <!-- <text class="header-cell">创建人</text> -->
          <text class="header-cell">供应商</text>
          <text class="header-cell">出库类型</text>
          <text class="header-cell">出库单号</text>
        </view>
        <view
          v-for="(item, index) in mainTableData"
          :key="index"
          class="table-row"
          :class="{
            selected: selectedMainRow && selectedMainRow.id === item.id,
          }"
          @click="selectMainRow(item)"
        >
          <view class="table-cell">
            <view class="custom-checkbox" @click.stop="selectMainRow(item)">
              <view
                class="checkbox-icon"
                :class="{
                  'checkbox-checked':
                    selectedMainRow && selectedMainRow.id === item.id,
                }"
              >
                <text
                  v-if="selectedMainRow && selectedMainRow.id === item.id"
                  class="check-mark"
                  >✓</text
                >
              </view>
            </view>
          </view>
          <text class="table-cell">{{
            item.ywDate ? dateHelperApi.formateTime(item.ywDate) : "-"
          }}</text>
          <text class="table-cell">{{ item.suppName || "-" }}</text>
          <text class="table-cell">{{ item.outType || "-" }}</text>
          <text class="table-cell">{{ item.mainNo || "-" }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- E. 明细表数据 -->
    <view class="material-table-section" v-if="selectedMainRow">
      <view class="section-header">
        <text class="section-title">出库明细表</text>
        <view class="statistics-info">
          <text class="stat-item">总重: {{ selectedTotalWeight }} KG</text>
          <text class="stat-item">总数量: {{ selectedTotalQuantity }}</text>
        </view>
      </view>
      <scroll-view class="table-scroll" scroll-y>
        <view class="table-row header">
          <text class="header-cell">选择</text>
          <text class="header-cell">物料编码</text>
          <text class="header-cell">物料名称</text>
          <text class="header-cell">规格</text>
          <text class="header-cell">数量</text>
          <text class="header-cell">重量(KG)</text>
          <text class="header-cell">单价</text>
          <text class="header-cell">金额</text>
        </view>
        <view
          v-for="(item, index) in detailTableData"
          :key="index"
          class="table-row"
          :class="{
            selected: selectedDetailRows.some((row) => row.id === item.id),
          }"
          @click="toggleDetailRowSelection(item)"
        >
          <view class="table-cell">
            <view
              class="custom-checkbox"
              @click.stop="toggleDetailRowSelection(item)"
            >
              <view
                class="checkbox-icon"
                :class="{
                  'checkbox-checked': selectedDetailRows.some(
                    (row) => row.id === item.id
                  ),
                }"
              >
                <text
                  v-if="selectedDetailRows.some((row) => row.id === item.id)"
                  class="check-mark"
                  >✓</text
                >
              </view>
            </view>
          </view>
          <text class="table-cell">{{
            item.materialCode || item.matCode || "-"
          }}</text>
          <text class="table-cell">{{
            item.materialName || item.matName || "-"
          }}</text>
          <text class="table-cell">{{
            item.specification || item.spec || "-"
          }}</text>
          <view class="table-cell quantity-cell">
            <input
              type="number"
              v-model.number="item.transCount"
              @input="onQuantityChange(item)"
              class="quantity-input large-input"
              placeholder="数量"
            />
          </view>
          <view class="table-cell quantity-cell">
            <input
              type="digit"
              v-model.number="item.prodCount"
              @input="onQuantityChange(item)"
              class="quantity-input large-input"
              placeholder="重量"
            />
          </view>
          <text class="table-cell">{{
            item.prodPrice || item.price || "-"
          }}</text>
          <text class="table-cell">{{
            (
              (item.prodCount || item.weight || 0) *
              (item.prodPrice || item.price || 0)
            ).toFixed(2)
          }}</text>
        </view>
      </scroll-view>
    </view>

    <!-- F. 底部操作栏 -->
    <view class="action-bar">
      <view class="action-row">
        <button class="btn-reset" @click="resetSelection">重置选择</button>
        <button class="btn-submit" @click="submitReverse">红冲出库</button>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { reverseApi } from "@/api/warehouse/reverse";
import { warehouseApi } from "@/api/warehouse/warehouse";
import { dateHelperApi } from "@/pages/smart/warehouse/utils/date-helper";

export default {
  name: "StockInReverse",
  data() {
    return {
      // 表单数据
      formData: {
        queryDate: dateHelperApi.getCurrentDate(),
        warehouseCode: "",
        warehouseName: "",
      },

      // 当前仓库信息
      currentWarehouse: {
        warehouseCode: "",
        warehouseName: "请选择仓库",
      },

      // 时间筛选器
      timeFilter: "today",
      // 时间范围
      timeRange: {
        startTime: "",
        endTime: "",
      },

      // 主表数据
      mainTableData: [],
      // 明细表数据
      detailTableData: [],
      // 选中的主表行
      selectedMainRow: null,
      // 选中的明细行
      selectedDetailRows: [],

      // 加载状态
      loading: false,
      // 仓库选项列表
      targetWarehouseOptions: [],
      // 当前仓库索引
      currentWarehouseIndex: -1,
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 选中的明细行总重量
    selectedTotalWeight() {
      return this.selectedDetailRows
        .reduce((total, item) => {
          return total + (parseFloat(item.prodCount) || 0);
        }, 0)
        .toFixed(3);
    },
    // 选中的明细行总数量
    selectedTotalQuantity() {
      return this.selectedDetailRows.reduce((total, item) => {
        return total + (parseInt(item.transCount) || 0);
      }, 0);
    },
  },
  onLoad() {
    this.loadCurrentWarehouse();
    this.loadWarehouseOptions(); // 加载仓库选项
    // 页面加载时初始化时间范围并加载数据
    this.handleTimeChange("today");
    this.$nextTick(() => {
      this.loadMainTableData();
    });
  },
  methods: {
    /* 加载当前仓库 */
    loadCurrentWarehouse() {
      const userConfig = this.$store.state.user.userConfig;
      if (userConfig && userConfig.wmName) {
        this.currentWarehouse = {
          warehouseCode: userConfig.wmCode || "DEFAULT",
          warehouseName: userConfig.wmName,
        };
        this.formData.warehouseCode = this.currentWarehouse.warehouseCode;
        this.formData.warehouseName = this.currentWarehouse.warehouseName;
      }
    },

    /* 加载仓库选项 */
    async loadWarehouseOptions() {
      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          dictType: "wm_name_po",
        };
        const response = await warehouseApi.getWarehouseList(params);
        if (response.code === 0) {
          // 将数据转换为下拉选项格式，根据API返回的字段名称
          this.targetWarehouseOptions = (response.data.list || []).map(
            (item) => ({
              value: item.value,
              text: item.label,
              warehouseName: item.label, // 用于显示
            })
          );
          console.log("目标仓库数据加载成功:", this.targetWarehouseOptions);

          // 如果当前有仓库，设置对应的索引
          if (this.currentWarehouse && this.currentWarehouse.warehouseName) {
            const index = this.targetWarehouseOptions.findIndex(
              (option) =>
                option.warehouseName === this.currentWarehouse.warehouseName
            );
            if (index !== -1) {
              this.currentWarehouseIndex = index;
            }
          }
        }
      } catch (error) {
        console.error("加载仓库选项失败:", error);
      }
    },

    /* 处理仓库选择变化 */
    handleWarehouseChange(e) {
      const index = e.detail.value;
      this.currentWarehouseIndex = index;
      const selectedWarehouse = this.targetWarehouseOptions[index];
      if (selectedWarehouse) {
        this.currentWarehouse = {
          warehouseCode: selectedWarehouse.value,
          warehouseName: selectedWarehouse.warehouseName,
        };
        this.formData.warehouseCode = selectedWarehouse.value;
        this.formData.warehouseName = selectedWarehouse.warehouseName;

        // 重新搜索数据
        this.loadMainTableData();
      }
    },

    /* 处理日期选择 */
    handleDateChange(e) {
      this.formData.queryDate = e.detail.value;
      this.loadMainTableData();
    },

    /* 时间选择处理 */
    handleTimeChange(timeFilter) {
      // 更新时间筛选器
      this.timeFilter = timeFilter;

      // 使用通用的updateDateRange函数
      const result = dateHelperApi.updateDateRange(timeFilter, {
        callback: ({ startDate, endDate }) => {
          // 更新时间范围
          this.timeRange = {
            startTime: startDate,
            endTime: endDate,
          };
        },
      });

      // 重新加载数据
      this.$nextTick(() => {
        this.loadMainTableData();
      });
    },

    /* 加载主表数据 */
    async loadMainTableData() {
      if (this.loading) return;
      this.loading = true;

      try {
        const params = {
          pageNo: 1,
          pageSize: 100,
          busStatus: "生效",
          warehouseName: this.currentWarehouse.warehouseName || "",
        };

        // 添加时间范围参数
        if (this.timeRange.startTime && this.timeRange.endTime) {
          params.ywDate = [this.timeRange.startTime, this.timeRange.endTime];
        }

        console.log("查询主表参数:", params);
        const response = await reverseApi.getPoStockOutMainPage(params);
        console.log("主表数据响应:", response);

        if (response.code === 0) {
          this.mainTableData = response.data.list || [];
          // 清空明细数据和选择
          this.detailTableData = [];
          this.selectedMainRow = null;
          this.selectedDetailRows = [];
        } else {
          uni.showToast({
            title: response.message || "加载主表数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载主表数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },

    /* 选择主表行 */
    async selectMainRow(row) {
      console.log("选择主表行:", row);
      if (this.selectedMainRow && this.selectedMainRow.id === row.id) {
        console.log("点击已选中的行，取消选择:", row);
        // 如果点击已选中的行，则取消选择
        this.selectedMainRow = null;
        this.detailTableData = [];
        this.selectedDetailRows = [];
        return;
      }

      console.log("选择新行，ID:", row.id);
      this.selectedMainRow = row;
      this.selectedDetailRows = []; // 清空明细选择

      // 加载对应的明细数据
      console.log("开始加载明细数据...");
      await this.loadDetailTableData(row.id);
      console.log("明细数据加载完成，数据量:", this.detailTableData.length);
    },

    /* 加载明细表数据 */
    async loadDetailTableData(mainId) {
      if (this.loading) return;
      this.loading = true;

      try {
        console.log("开始加载明细表数据，主表ID:", mainId);
        const params = {
          pageNo: 1,
          pageSize: 100,
          mainId: mainId,
        };
        const response = await reverseApi.getPoStockOut(params);
        console.log("明细表数据响应:", response);
        console.log("响应数据结构:", JSON.stringify(response, null, 2));

        if (response.code === 0) {
          // 检查数据结构，可能是 response.data 直接是数组，或者 response.data.list 是数组
          let detailData = [];
          if (Array.isArray(response.data)) {
            detailData = response.data;
          } else if (response.data && Array.isArray(response.data.list)) {
            detailData = response.data.list;
          } else if (response.data && response.data.records) {
            detailData = response.data.records;
          } else if (response.data) {
            // 如果data是对象，尝试从中提取数组
            const keys = Object.keys(response.data);
            console.log("响应data的键:", keys);
            for (let key of keys) {
              if (Array.isArray(response.data[key])) {
                detailData = response.data[key];
                console.log("找到数组数据在键:", key);
                break;
              }
            }
            if (detailData.length === 0) {
              console.warn("未找到明细数据数组，尝试将整个data作为单个记录");
              detailData = [response.data]; // 作为单个记录
            }
          } else {
            detailData = [];
            console.warn("未找到明细数据，数据结构:", response.data);
          }

          // 确保所有项目都有必要的字段
          this.detailTableData = detailData.map((item) => ({
            ...item,
            transCount: item.transCount || item.quantity || 0,
            prodCount: item.prodCount || item.weight || item.quantity || 0,
            prodPrice: item.prodPrice || item.price || 0,
            materialCode: item.materialCode || item.matCode || "",
            materialName: item.materialName || item.matName || "",
            specification: item.specification || item.spec || "",
            checked: false, // 添加选中状态
          }));

          console.log("处理后的明细表数据:", this.detailTableData);

          // 如果没有数据，显示提示
          if (this.detailTableData.length === 0) {
            uni.showToast({
              title: "该出库单暂无明细数据",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.message || "加载明细数据失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("加载明细数据失败:", error);
        uni.showToast({
          title: "请求失败: " + error.message,
          icon: "none",
        });
      }

      this.loading = false;
    },

    /* 切换明细行选择 */
    toggleDetailRowSelection(row) {
      const index = this.selectedDetailRows.findIndex(
        (item) => item.id === row.id
      );
      if (index === -1) {
        this.selectedDetailRows.push(row);
      } else {
        this.selectedDetailRows.splice(index, 1);
      }
    },

    /* 数量或重量变更处理 */
    onQuantityChange(item) {
      // 重新计算金额
      this.$forceUpdate();
    },

    /* 重置选择 */
    resetSelection() {
      this.selectedDetailRows = [];
    },

    /* 提交红冲 */
    async submitReverse() {
      if (this.selectedDetailRows.length === 0) {
        uni.showToast({
          title: "请选择要红冲的明细数据",
          icon: "none",
        });
        return;
      }

      // 显示加载状态
      uni.showLoading({
        title: "正在提交...",
        mask: true,
      });

      try {
        // 构建红冲数据结构 - 参考出库创建页面的完整参数结构
        const reverseData = {
          // 主表信息
          id: null, // 新增时传null，让后端生成新的红冲记录ID
          mainNo: this.selectedMainRow.mainNo || "", // 系统自动生成新的红冲出库单号
          outType: this.selectedMainRow.outType || "领料出库", // 出库类型
          warehouseCode: this.selectedMainRow.warehouseCode || "", // 仓库编码
          warehouseName: this.selectedMainRow.warehouseName || "", // 仓库名称
          ywDate: dateHelperApi.formateTime(new Date()), // 业务日期（红冲日期）
          busMemo: `红冲原出库单：${this.selectedMainRow.mainNo || ""}`, // 业务备注

          // 关联原出库单信息
          sourceMainId: this.selectedMainRow.id, // 原出库单ID
          sourceMainNo: this.selectedMainRow.mainNo, // 原出库单号

          // 明细数据
          details: this.selectedDetailRows.map((item) => ({
            id: null, // 新增时传null，让后端生成新的明细记录ID
            materialCode: item.materialCode || item.matCode || "",
            materialName: item.materialName || item.matName || "",
            spec: item.specification || item.spec || "",
            prodCount: parseFloat(item.prodCount) || 0, // 重量（红冲数量）
            countUnit: "KG", // 数量单位
            transCount: parseInt(item.transCount) || 0, // 数量（红冲数量）
            tranUnit: item.tranUnit || "件", // 辅助单位
            prodPrice: parseFloat(item.prodPrice) || 0, // 单价
            budgetAmount:
              (parseFloat(item.prodCount) || 0) *
              (parseFloat(item.prodPrice) || 0), // 金额

            // 关联原明细信息
            sourceDetailId: item.id, // 原明细ID

            // 其他字段，保持与原出库单一致
            warehouseCode: this.selectedMainRow.warehouseCode || "",
            warehouseName: this.selectedMainRow.warehouseName || "",
            brand: item.brand || "",
            prodCompany: item.prodCompany || "",
            categoryName: item.categoryName || "",
            picNo: item.picNo || "",
            batchNoSerial: item.batchNoSerial || "",
            steelGradeName: item.steelGradeName || "",
            standardName: item.standardName || "",
            soDiameter: item.soDiameter || "",
            soWidth: item.soWidth || "",
            soThick: item.soThick || "",
            poContractDetailCode: item.poContractDetailCode || "",
            soLength: item.soLength || "",
          })),
        };

        console.log("红冲提交数据:", reverseData);

        // 提交前确认
        const confirmRes = await this.showSubmitConfirm(reverseData);
        if (!confirmRes) {
          uni.hideLoading();
          return;
        }

        const response = await reverseApi.reverseStockOut(reverseData);
        console.log("红冲响应:", response);

        if (response.code === 0) {
          await this.handleSubmitSuccess(response);
        } else {
          throw new Error(response.message || "红冲失败");
        }
      } catch (error) {
        await this.handleSubmitException(error);
      } finally {
        uni.hideLoading();
      }
    },

    // 显示提交确认
    showSubmitConfirm(reverseData) {
      return new Promise((resolve) => {
        const materialCount = reverseData.details.length;
        const totalWeight = reverseData.details.reduce(
          (sum, item) => sum + (Number(item.prodCount) || 0),
          0
        );
        const totalQuantity = reverseData.details.reduce(
          (sum, item) => sum + (Number(item.transCount) || 0),
          0
        );

        uni.showModal({
          title: "确认红冲",
          content: `共${materialCount}条物料，总重量：${totalWeight.toFixed(
            3
          )}KG，总数量：${totalQuantity}，是否确认红冲？`,
          confirmText: "确认",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
        });
      });
    },

    // 处理提交成功
    async handleSubmitSuccess(res) {
      uni.showToast({
        title: "红冲成功",
        icon: "success",
        duration: 2000,
      });

      // 记录成功日志
      console.log("红冲成功:", res.data);

      // 重新加载数据
      this.loadMainTableData();

      // 清空选择
      this.selectedMainRow = null;
      this.detailTableData = [];
      this.selectedDetailRows = [];
    },

    // 处理提交异常
    async handleSubmitException(error) {
      console.error("红冲异常:", error);

      let errorMsg = "红冲失败，请重试";

      // 网络错误处理
      if (error.message && error.message.includes("Network")) {
        errorMsg = "网络连接失败，请检查网络后重试";
      } else if (error.code === "ECONNABORTED") {
        errorMsg = "请求超时，请稍后重试";
      } else if (error.response && error.response.status) {
        switch (error.response.status) {
          case 400:
            errorMsg = "请求参数错误，请检查输入数据";
            break;
          case 401:
            errorMsg = "登录已过期，请重新登录";
            break;
          case 403:
            errorMsg = "没有权限执行此操作";
            break;
          case 500:
            errorMsg = "服务器错误，请稍后重试";
            break;
          default:
            errorMsg = `服务器错误 (${error.response.status})，请稍后重试`;
        }
      }

      uni.showModal({
        title: "红冲失败",
        content: errorMsg,
        showCancel: false,
        confirmText: "知道了",
      });
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/pages/smart/scss/create.scss";
</style>
